package misty.mispic.app.ui.thumb

import com.google.common.eventbus.Subscribe
import com.sun.javafx.css.StyleManager
import groovy.io.FileType
import groovy.transform.CompileStatic
import javafx.application.Platform
import javafx.beans.value.ChangeListener
import javafx.collections.FXCollections
import javafx.collections.ObservableList as FXObservableList
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Control
import javafx.scene.control.Skin
import javafx.scene.image.Image
import javafx.scene.layout.BorderPane
import javafx.scene.layout.StackPane
import misty.mispic.app.comp.ThumbGridCell
import misty.mispic.app.event.EventBus
import misty.mispic.app.event.PhotoEvent
import misty.mispic.app.event.ThumbEvent
import misty.mispic.app.ui.CSS
import org.controlsfx.control.GridView

import java.nio.file.Path

/**
 * Created by Misty on 2015/1/25.
 */
@CompileStatic
class Thumb2 extends Control implements Initializable {
    static {
        StyleManager.instance.addUserAgentStylesheet(CSS.thumb.location)
    }

    private static List<String> EXTENSIONS = ['BMP', 'PCX', 'TIFF', 'GIF', 'JPG', 'JPEG', 'TGA',
                                              'EXIF', 'FPX', 'SVG', 'PSD', 'CDR', 'PCD', 'DXF',
                                              'UFO', 'EPS', 'AI', 'PNG', 'HDRI', 'RAW']

    @FXML
    private StackPane mThumbRoot

    @FXML
    private BorderPane mIndicator

    private GridView mThumbGrid

    private FXObservableList images = FXCollections.observableArrayList()
    private Path lastPath
    private Image lastImage

    Thumb2() {
        sceneProperty().addListener({ obs, ov, nv ->
            if (ov) {
                EventBus.unregister(this)
            }
            if (nv) {
                EventBus.register(this)
            }
        } as ChangeListener)
    }

    @Override
    void initialize(URL location, ResourceBundle resources) {
        def grid = new GridView(images)
        grid.cellWidth = 160
        grid.cellHeight = 140
        grid.horizontalCellSpacing = 5
        grid.verticalCellSpacing = 5
        grid.cellFactory = { new ThumbGridCell() }
        mThumbRoot.getChildren() << grid
        grid.toBack()
        mThumbGrid = grid
    }

    @Override
    protected Skin createDefaultSkin() {
        return new Thumb2Skin(this)
    }

    @Subscribe
    void showImages(ThumbEvent.Show show) {
        if (!show.path) {
            return
        }
        if (show.path.equals(lastPath)) {
            return
        }
        lastPath = show.path
        mIndicator.setVisible(true)
        new Thread({
            try {
                def lst = []
                show.path.eachFile(FileType.FILES, { Path p ->
                    def fn = p.fileName.toString()
                    def ext = fn.split(/\./)[-1]
                    if (EXTENSIONS.any { it.equalsIgnoreCase(ext) }) {
                        def img = new Image(p.toUri().toURL().toExternalForm(), 160, 120, true, true, true)
                        lst << img
                    }
                })
                Platform.runLater {
                    images.clear()
                    images.setAll(lst)
                    mIndicator.setVisible(false)
                }
            } catch (ex) {
                ex.printStackTrace()
            }
        }).start()
    }

    @Subscribe
    void showImage(PhotoEvent.Show show) {
        lastImage = show.thumb
    }

    @Subscribe
    void nextImage(ThumbEvent.Next next) {
        println "show next"
        def idx = images.indexOf(lastImage) + 1
        if (images.size() > idx) {
            EventBus.post(new PhotoEvent.Show(images.get(idx) as Image))
        }
    }

    @Subscribe
    void prevImage(ThumbEvent.Prev prev) {
        println "show prev"
        def idx = images.indexOf(lastImage) - 1
        if (idx >= 0) {
            EventBus.post(new PhotoEvent.Show(images.get(idx) as Image))
        }
    }
}
